<template>
	<div class="systemSettings">
		<el-tabs v-model="activeName" @tab-click="handleClick">
			<el-tab-pane label="系统配置" name="system">
				<div class="system-table">
					<Table :tableData="tableData">
						<template v-slot:key>
							<el-table-column width="auto" align="center" label="配置项">
								<template slot-scope="scope">
									<span>{{ getConfigType(scope.row.itemKey) }}</span>
								</template>
							</el-table-column>
						</template>
						<template v-slot:status>
							<el-table-column width="auto" align="center" label="状态">
								<template slot-scope="scope">
									<span>{{ scope.row.status ? '开启' : '关闭' }}</span>
								</template>
							</el-table-column>
						</template>
						<template v-slot:btn>
							<el-table-column width="310px" align="center" label="">
								<template slot-scope="scope">
									<el-button size="mini" class="set-btn" :class="scope.row.status ? 'disabled' : ''"
										:disabled="scope.row.status" @click="showConfiguration(scope.$index, scope.row)">
										配置
									</el-button>
									<el-button size="mini" class="open-btn" v-if="!scope.row.status"
										@click="changeStatus(scope.row)">启用</el-button>
									<el-button size="mini" class="stop-btn" v-else
										@click="changeStatus(scope.row)">停用</el-button>
								</template>
							</el-table-column>
						</template>
					</Table>
				</div>
			</el-tab-pane>
		</el-tabs>
		<WaterMark :showWatermark="showWatermark" @cancelWatermark="cancelWatermark" @submitWatermark="submitWatermark">
		</WaterMark>
		<TimeStamp ref="times" v-if="showTimeStamp" :showTimeStamp="showTimeStamp" :time="time" :isTime="isTime"
			:isActive="isActive" @cancelTimeStamp="cancelTimeStamp" @submitTimeStamp="submitTimeStamp"
			@clickTime="clickTime"></TimeStamp>
		<AgentIdMark :showAgentMark="showAgentMark" v-if="showAgentMark" :agnetRadio="agnetRadio" @cancel="cancelAgentMark"
			@ok="applyAgentMark" />
		<DataMasking :visible.sync="showDataMasking" v-if="showDataMasking" :id="configId" :initData="dataMaskingData">
		</DataMasking>
		<WatermarkConfig :showWatermarkConfig="showWatermarkConfig" v-if="showWatermarkConfig"
			:waterMarkData="waterMarkData" @cancelWatermark="cancelWatermarkConfig" @saveWatermark="saveWatermark" />
		<CallWatermarkAddition :showCallWatermarkAddition="showCallWatermarkAddition" v-if="showCallWatermarkAddition"
			:callWatermarkData="callWatermarkData" @cancelCallWatermarkAddition="cancelCallWatermarkAddition"
			@saveCallWatermarkAddition="saveCallWatermarkAddition" />
		<AddCallAgentId :showAddCallAgentId="showAddCallAgentId" v-if="showAddCallAgentId" :addCallRadio="addCallRadio"
			@cancelAddCallAgentId="cancelAddCallAgentId" @saveAddCallAgentId="saveAddCallAgentId" />
		<ScreenWatermarkDialog v-if="showScreenWatermarkDialog" :visible="showScreenWatermarkDialog"
			@cancel="showScreenWatermarkDialog = false" :id="configId" :option="screenWatermarkData" />
	</div>
</template>
<script>
import Table from '../components/Table.vue';
import WaterMark from './Watermark.vue';
import TimeStamp from './TimeStamp.vue';
import AgentIdMark from './AgentIdMark.vue';
import DataMasking from './DataMasking.vue';
import WatermarkConfig from './WatermarkConfig.vue';
import CallWatermarkAddition from './CallWatermarkAddition.vue';
import AddCallAgentId from './AddCallAgentId.vue';
import { getConfigList, setConfigStatus, updateConfig } from '../../api/api';
import { mapMutations, mapState } from 'vuex';
import ScreenWatermarkDialog from './ScreenWatermarkDialog.vue';
import { addScreenWatermark, removeScreenWatermark, appendToken } from '@/utils/tool.js';

export default {
	components: {
		Table,
		WaterMark,
		TimeStamp,
		AgentIdMark,
		DataMasking,
		WatermarkConfig,
		CallWatermarkAddition,
		AddCallAgentId,
		ScreenWatermarkDialog
	},
	props: {},
	data() {
		return {
			configId: null, // 配置 ID
			showWatermark: false, //配置水印
			showTimeStamp: false, //配置时间戳
			showAgentMark: false, // 配置坐席工号水印
			showDataMasking: false, //脱敏配置
			dataMaskingData: {},
			activeName: 'system', //modal默认值
			isActive: 0, //边框样式
			showBtn: true, //启用或停用按钮
			agnetRadio: '', // 默认选择坐席工号
			time: [
				{ year: '2013-08-22 ', hour: '18:54:13', id: 1 },
				{ year: '2013/08/22 ', hour: '18:54:13', id: 2 },
				{ year: '2013-08-22 ', hour: '18:54:13', id: 3 },
				{ year: '2013/08/22 ', hour: '18:54:13', id: 4 },
				{ year: '2013/08/22  ', hour: '18:54:13 Tue', id: 5 },
				{ year: '2013/08/22 ', hour: '18:54:13 Tue', id: 6 }
			],
			//显示在video标签上的时间戳
			isTime: {
				year: '',
				hour: '',
				id: ''
			},
			tableData: {
				sort: false,
				checkedGroup: true,
				//表头
				tableHead: [],
				//表单数据
				tableConent: [],
				showIndex: true,
				showCheck: false
			},
			showWatermarkConfig: false, // 录像文件水印配置显示隐藏
			// 录像文件水印配置 数据
			waterMarkData: {
				watermark: '',
				scale: 0.1,
				width: '',
				height: '',
				position: ''
			},
			showCallWatermarkAddition: false, //通话水印添加显示隐藏
			// /通话水数据
			callWatermarkData: {
				side: 1, // 展示端：0-不做展示, 1-访客端, 2-座席端, 3-访客端和座席端都展示
				watermark: '', // 水印地址
				scale: 0.1, // 缩放比例：1.0
				position: '', // 位置：nw-左上方, n-上方, ne-右上方, sw-左下方, s-下方， se-右下方
				width: '',
				height: ''
			},
			showAddCallAgentId: false, // 通话坐席ID添加 显示隐藏
			addCallRadio: '', //通话坐席ID添加 展示方位  例如 ： 正上方
			showScreenWatermarkDialog: false, // 屏幕水印
			screenWatermarkData: {}
		};
	},
	created() { },
	mounted() {
		this.getConfigList();
	},
	computed: {
		...mapState({
			radioType: state => state.systemSetting.radioType
		})
	},
	methods: {
		...mapMutations('systemSetting', ['SET_RADIO_TYPE', 'SET_SHOW_VIDEO']),
		getConfigType(type) {
			let title = '';
			switch (type) {
				case 'videoTimestamp':
					title = '录像文件时间戳配置';
					break;
				case 'videoWatermark':
					title = '录像文件水印配置';
					break;
				case 'videoAgentId':
					title = '录像文件坐席ID水印配置';
					break;
				// 2219 脱敏配置升级 ,注释原来系统配置项
				// case 'dataMasking':
				// 	title = '关键字脱敏配置';
				// 	break;
				case 'callWatermark':
					title = '访客端通话水印添加';
					break;
				case 'callAgentId':
					title = '访客端通话坐席ID添加';
					break;
				case 'screenWatermark':
					title = '屏幕水印';
					break;
				default:
					title = '';
					break;
			}
			return title;
		},

		//获取系统设置下拉列表
		async getConfigList() {
			try {
				let data = await getConfigList();
				console.log('获取系统设置下拉列表', data.data);
				this.tableData.tableConent = data.data.list.map(item => {
					if (item.itemData.watermark) {
						item.itemData.watermark = appendToken(item.itemData.watermark);
					}
					return { id: item.id, itemKey: item.itemKey, status: item.status, itemData: item.itemData };
				});
				// const  = {
				// 	id: 999,
				// 	itemData: {},
				// 	itemKey: 'DataMasking',
				// 	status: false
				// };
				// this.tableData.tableConent.push(encryption);
				this.tableData.tableConent.splice(3, 1);
				console.log('获取系统设置下拉列表', this.tableData.tableConent);
				const item = data.data.list.find(item => item.itemKey === 'screenWatermark');
				if (item?.status) {
					addScreenWatermark(item.itemData.param);
				} else {
					removeScreenWatermark();
				}
			} catch (error) {
				console.log(error);
				this.$requestApiError(error, () => {
					this.$router.push('/');
				});
			}
		},

		//配置水印
		showConfiguration(index, row) {
			switch (row.itemKey) {
				case 'videoTimestamp':
					this.isTime = this.time.find(item => item.id === row.itemData.timestamp);
					this.$store.commit('SET_RADIO_TYPE', row.itemData.position);
					this.isActive = row.itemData.timestamp;
					this.configId = row.id;
					this.showTimeStamp = true;
					break;
				case 'videoAgentId':
					this.showAgentMark = true;
					this.agnetRadio = row.itemData.position || '';
					this.configId = row.id;
					break;
				case 'videoWatermark':
					console.log('videoWatermark');
					this.configId = row.id;
					this.waterMarkData = row.itemData || {};
					this.showWatermarkConfig = true;
					break;
				// case 'dataMasking':
				// 	console.log('dataMasking', row);
				// 	this.dataMaskingData = row;
				// 	this.configId = row.id;
				// 	this.showDataMasking = true;
				// 	break;
				case 'callWatermark':
					this.configId = row.id;
					this.callWatermarkData = row.itemData || {};
					this.showCallWatermarkAddition = true;
					break;
				case 'callAgentId':
					this.configId = row.id;
					this.showAddCallAgentId = true;
					this.addCallRadio = row.itemData.position || '';
					break;
				case 'screenWatermark':
					this.configId = row.id;
					this.screenWatermarkData = row.itemData.param || {};
					this.showScreenWatermarkDialog = true;
					break;
				default:
					break;
			}
		},
		//关闭水印弹窗
		cancelWatermark() {
			this.showWatermark = false;
		},
		//应用水印
		submitWatermark() {
			this.showWatermark = false;
			this.$message({
				message: '保存成功',
				type: 'success'
			});
		},
		//取消时间戳
		cancelTimeStamp() {
			this.showTimeStamp = false;
			this.isActive = '';
			this.showVideo = false;
			this.$store.commit('SET_SHOW_VIDEO', false);
		},

		// 取消配置坐席工号
		cancelAgentMark() {
			this.showAgentMark = false;
		},
		// 应用坐席工号水印
		async applyAgentMark(data) {
			try {
				await updateConfig(this.configId, data);
				this.$message({
					message: '保存成功',
					type: 'success'
				});
				this.showAgentMark = false;
			} catch (e) {
				switch (e.code) {
					case 1002:
						this.$message.error('应用失败，正在被使用中！');
						break;
					case 1101:
						this.$message.error('应用失败，请求权限拒绝！');
						break;
					case 1201:
						this.$message.error('应用失败，数据写入错误！');
						break;
					case 1301:
						this.$message.error('应用失败，无效的配置！');
						break;
					default:
						this.$message.error(`应用失败,${e.message}`);
						break;
				}
			} finally {
				this.getConfigList();
			}
		},
		//更新配置项
		async updateConfigFn(id, value) {
			try {
				await updateConfig(id, value);
				this.showTimeStamp = false;
				this.$store.commit('SET_SHOW_VIDEO', false);
				this.$message({
					message: '保存成功',
					type: 'success'
				});
			} catch (error) {
				switch (error.code) {
					case 1002:
						this.$message.error('应用失败，正在被使用中！');
						break;
					case 1101:
						this.$message.error('应用失败，请求权限拒绝！');
						break;
					case 1201:
						this.$message.error('应用失败，数据写入错误！');
						break;
					case 1301:
						this.$message.error('应用失败，无效的配置！');
						break;
					default:
						this.$message.error(`应用失败,${error.message}`);
						break;
				}
			} finally {
				this.getConfigList();
			}
		},

		//应用时间戳
		submitTimeStamp(timestamp, position) {
			if (timestamp === 0 || !position) {
				this.$message({
					message: '请选择时间戳类型/显示位置',
					type: 'error'
				});
				return;
			}
			let id = this.configId;
			let data = { value: { timestamp, position } };
			this.updateConfigFn(id, data);
		},
		//设置配置项状态
		async setConfigStatus(id, status) {
			try {
				await setConfigStatus(id, { status });
				this.$message({
					message: `${status ? '启用' : '停用'}成功`,
					type: 'success'
				});
			} catch (error) {
				console.log(error);
				this.$message({
					message: `${status ? '启用' : '停用'}失败`,
					type: 'error'
				});
			} finally {
				this.getConfigList();
			}
		},
		//启用/停用
		async changeStatus(row) {
			console.log(row);
			let data = row.itemData || {};
			let type = row.itemKey || '';
			// 未配置屏幕水印时使用默认值
			if (type === 'screenWatermark' && JSON.stringify(data) === '{}') {
				const param = {
					content: ['username', 'loginTime'],
					font: 'SimSun',
					fontSize: 20,
					color: '#000000',
					width: 300,
					height: 300,
					x: 0,
					y: 260,
					alpha: 10,
					angle: -45
				};
				const value = {
					value: {
						param: param,
					}
				};
				try {
					await updateConfig(row.id, value)
					this.setConfigStatus(row.id, !row.status);
				} catch (error) {
					console.log(error);
				}
				return;
			}
			// 接口返回的是 itemData: {} 点击启用 无效果
			if (JSON.stringify(data) === '{}') {
				switch (type) {
					case 'videoTimestamp':
						this.$message({
							message: '当前未配置时间戳，请配置后重新启用',
							type: 'error'
						});
						break;
					case 'videoAgentId':
						this.$message({
							message: '当前未配置坐席ID，请配置后重新启用',
							type: 'error'
						});
						break;
					case 'videoWatermark':
						this.$message({
							message: '当前未配置图片水印，请配置后重新启用',
							type: 'error'
						});
						break;
					case 'callWatermark':
						this.$message({
							message: '当前未配置图片水印，请配置后重新启用',
							type: 'error'
						});
						break;
					// case 'screenWatermark':
					// 	this.$message({
					// 		message: '当前未配置屏幕水印，请配置后重新启用',
					// 		type: 'error'
					// 	});
					// 	break;
					default:
						break;
				}
				return;
			}
			//当后端接口返回 itemData: {side: 0, scale: 1, position: "nw", watermark: ""}  初始化没配置水映图片 watermark ，录像文件水印配置，录像文件水印配置 点击配置按钮要 toast 弹框提示
			let watermark = row.itemData.watermark || '';
			if (!watermark && ['videoWatermark', 'callWatermark'].includes(type)) {
				switch (type) {
					case 'videoWatermark':
						this.$message({
							message: '当前未配置图片水印，请配置后重新启用',
							type: 'error'
						});
						break;
					case 'callWatermark':
						this.$message({
							message: '当前未配置图片水印，请配置后重新启用',
							type: 'error'
						});
						break;
					default:
						break;
				}
				return;
			}
			this.setConfigStatus(row.id, !row.status);
		},
		clickTime(item) {
			// console.log(item);
			this.isTime = {
				id: item.id,
				hour: item.hour,
				year: item.year
			};
			console.log(this.isTime);
		},
		//  录像文件水印配置取消和保存事件
		cancelWatermarkConfig() {
			this.showWatermarkConfig = false;
		},
		async saveWatermark(value) {
			this.showWatermarkConfig = false;
			try {
				await updateConfig(this.configId, value);
				this.$message({
					message: '保存成功',
					type: 'success'
				});
				this.showAddCallAgentId = false;
			} catch (e) {
				switch (e.code) {
					case 1002:
						this.$message.error('应用失败，正在被使用中！');
						break;
					case 1101:
						this.$message.error('应用失败，请求权限拒绝！');
						break;
					case 1201:
						this.$message.error('应用失败，数据写入错误！');
						break;
					case 1301:
						this.$message.error('应用失败，无效的水印！');
						break;
					default:
						this.$message.error(`应用失败,${e.message}`);
						break;
				}
			} finally {
				this.getConfigList();
			}
		},
		// 通话水印添加 取消和保存事件
		cancelCallWatermarkAddition() {
			this.showCallWatermarkAddition = false;
		},
		async saveCallWatermarkAddition(value) {
			try {
				await updateConfig(this.configId, value);
				this.$message({
					message: '保存成功',
					type: 'success'
				});
				this.showCallWatermarkAddition = false;
			} catch (e) {
				switch (e.code) {
					case 1002:
						this.$message.error('应用失败，正在被使用中！');
						break;
					case 1101:
						this.$message.error('应用失败，请求权限拒绝！');
						break;
					case 1201:
						this.$message.error('应用失败，数据写入错误！');
						break;
					case 1301:
						this.$message.error('应用失败，无效的水印！');
						break;
					default:
						this.$message.error(`应用失败,${e.message}`);
						break;
				}
			} finally {
				this.getConfigList();
			}
		},
		// 通话坐席ID添加 取消和保存事件
		cancelAddCallAgentId() {
			this.showAddCallAgentId = false;
		},
		async saveAddCallAgentId(value) {
			try {
				await updateConfig(this.configId, value);
				this.$message({
					message: '保存成功',
					type: 'success'
				});
				this.showAddCallAgentId = false;
			} catch (e) {
				switch (e.code) {
					case 1002:
						this.$message.error('应用失败，正在被使用中！');
						break;
					case 1101:
						this.$message.error('应用失败，请求权限拒绝！');
						break;
					case 1201:
						this.$message.error('应用失败，数据写入错误！');
						break;
					case 1301:
						this.$message.error('应用失败，无效的水印！');
						break;
					default:
						this.$message.error(`应用失败,${e.message}`);
						break;
				}
			} finally {
				this.getConfigList();
			}
		}
	}
};
</script>
<style lang="less" scoped>
.systemSettings {
	.system-table {
		padding-top: 14px;
		padding-left: 18px;

		.table {
			background: #ffffff;
			border: 1px solid #ebedef;
			border-radius: 4px;
		}

		.set-btn {
			color: #fff;
			background-color: #6384fe;
			border-radius: 4px;
		}

		.open-btn {
			background-color: #e6a23c;
			color: #fff;
			border-radius: 4px;
		}

		.stop-btn {
			color: #fff;
			background-color: #ef5753;
			border-radius: 4px;
		}

		.disabled {
			background-color: #999999;
		}
	}
}
</style>

<style lang="less">
.systemSettings {
	.table .el-table th {
		background: #f8f8f9;
	}
}
</style>
